package main

import (
	"fmt"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/toolkits/pkg/file"
)

func main() {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	r.GET("/api/integrations", list)

	r.GET("/api/integration/:dir/overview", overview)
	r.GET("/api/integration/:dir/configuration", configuration)
	r.GET("/api/integration/:dir/dashboard", dashboard)
	r.GET("/api/integration/:dir/metrics", metrics)
	r.GET("/api/integration/:dir/monitors", monitors)

	configNoRoute(r)

	if len(os.Args) != 2 {
		fmt.Println("arg: <listen> missed")
		return
	}

	listen := os.Args[1]
	fmt.Println("listen:", listen)
	r.Run(listen)
}

type Integration struct {
	Name        string `yaml:"name" json:"name"`
	Label       string `yaml:"label" json:"label"`
	Logo        string `yaml:"logo" json:"logo"`
	Description string `yaml:"description" json:"description"`
}

func list(c *gin.Context) {
	var integrations []Integration
	err := file.ReadYaml("index.yaml", &integrations)
	if err != nil {
		c.String(http.StatusInternalServerError, err.Error())
		return
	}

	c.JSON(200, integrations)
}

func configNoRoute(r *gin.Engine) {
	r.NoRoute(func(c *gin.Context) {
		if strings.Contains(c.Request.URL.Path, "..") {
			c.AbortWithStatus(404)
			return
		}

		arr := strings.Split(c.Request.URL.Path, ".")
		suffix := arr[len(arr)-1]
		switch suffix {
		case "png", "jpeg", "jpg", "svg", "ico", "gif", "css", "js", "html", "htm", "gz", "zip", "map":
			c.File(path.Join(strings.Split("./"+c.Request.URL.Path, "/")...))
		default:
			c.AbortWithStatus(404)
		}
	})
}

func overview(c *gin.Context) {
	c.File(filepath.Join(c.Param("dir"), "overview.md"))
}

func configuration(c *gin.Context) {
	c.File(filepath.Join(c.Param("dir"), "configuration.md"))
}

func dashboard(c *gin.Context) {
	c.File(filepath.Join(c.Param("dir"), "dashboard.md"))
}

func metrics(c *gin.Context) {
	c.File(filepath.Join(c.Param("dir"), "metrics.md"))
}

func monitors(c *gin.Context) {
	c.File(filepath.Join(c.Param("dir"), "monitors.md"))
}
